<!--  固定表 -->
<template>
  <div>
    <div class="flex">
      <div class="flex-left">
        <div class="navigationBar">
          <label>资源分类</label>
          <span @click="showFolder()"
            ><i class="el-icon el-icon-circle-plus"></i
          ></span>
        </div>
        <div class="flex-tree">
          <el-tree
            ref="tree"
            :data="data"
            node-key="id"
            :render-content="renderContent"
            @node-click="handleNodeClick"
            :highlight-current="true"
          >
          </el-tree>

          <!-- <div
						v-if="data.length == 0"
						style="text-align: center; margin-top: 100px; color: #666"
					>
						暂无数据
					</div> -->
        </div>
      </div>
      <div class="flex-right">
        <navigation-bar>
          <div class="searchContent">
            <!-- <el-input
							v-model="username"
							placeholder="请输入资源名称"
							size="mini"
							style="width: 150px; margin-right: 10px"
						></el-input>
						<custom-button
							type="search"
							style="margin-right: 10px"
							@searchClick="searchClick"
						></custom-button>
						<custom-button
							type="reset"
							style="margin-right: 10px"
							@resetClick="resetClick"
						></custom-button> -->
            <custom-button type="add" @addClick="addClick"></custom-button>
            <!-- <el-button
							size="mini"
							style="
								margin-right: 10px;
								background-color: #fc6a6e;
								color: #fff;
								border: none;
							"
							@click="deleteAll"
						>
							<i class="el-icon-delete"></i> 批量删除
						</el-button> -->
          </div>
        </navigation-bar>
        <!-- @lookViewRow="lookViewRow" -->
        <table-index
          :dataSource="dataSource"
          :tableColumns="tableColumns"
          :btnList="btnList"
          :pageSize="pageSize"
          :pageCount="pageCount"
          :pageNo="pageNo"
          @pageChange="pageChange"
          @downloadRow="downloadRow"
          @deleteRow="deleteRow"
          @editRow="editRow"
          @lookViewRow="lookViewRow"
          :height="curHeight"
          @handleSelectionChange="handleSelectionChange"
        ></table-index>
      </div>
    </div>
    <div v-if="dialogShow">
      <custom-dialog
        :title="dialogTitle"
        size="large"
        @dialogClose="dialogClose"
      >
        <div>
          <resourceAdd
            @getData="getData"
            @submitCancel="dialogShow = false"
          ></resourceAdd>
        </div>
      </custom-dialog>
    </div>

    <div v-if="dialogFolderShow">
      <custom-dialog
        :title="dialogFolderTitle"
        size="large"
        @dialogClose="dialogFolderClose"
      >
        <form-index
          :formConfig="formConfigFolder"
          @submit="folderSubmit"
          :type="typeFolder"
          @formInputChange="formInputFolderChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>

    <div v-if="showloading">
      <loadingMask></loadingMask>
    </div>

    <div v-if="dialogEditShow">
      <custom-dialog
        title="编辑资源"
        size="large"
        @dialogClose="dialogEditShow = false"
      >
        <div>
          <resourceEdit
            :curDesc="fileInfo.Description"
            :curName="fileInfo.FileName"
            @getData="getDataEdit"
            @submitCancel="dialogEditShow = false"
          ></resourceEdit>
        </div>
      </custom-dialog>
    </div>
    <div v-if="showPwdJudge">
      <pwdJudge @close="showPwdJudge = false" @success="startDown"></pwdJudge>
    </div>
  </div>
</template>

<script>
import { presetFieldsForm } from "@/assets/form/managementCenter/expandManage/presetFieldsForm";
import { resourceFolderForm } from "@/assets/form/managementCenter/resourceFolderForm";
import customDialog from "@/components/customComponents/customDialog";
import customButton from "@/components/customComponents/customForm/customButton";
import formIndex from "@/components/customComponents/customForm/formIndex";
// import singleTable from "@/components/customComponents/customeTable/singleTable.vue"
import tableIndex from "@/components/customComponents/customeTable/tableHeightIndex";
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import { AjaxCommon, fileAddress } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
import { Utility } from "@/libs/utility";
import loadingMask from "@/components/customComponents/loading";
import resourceAdd from "./resourceAdd.vue";
import resourceEdit from "./resourceEdit.vue";
import pwdJudge from "@/components/customComponents/pwdJudge";
export default {
  components: {
    navigationBar,
    customButton,
    tableIndex,
    customDialog,
    // singleTable,
    formIndex,
    resourceAdd,
    resourceEdit,
    loadingMask,
    pwdJudge,
  },
  data() {
    return {
      showPwdJudge: false,
      currentSelectDown: {}, // 存储当前点击的那行数据
      dialogEditShow: false,
      publicPath: fileAddress + "\\",
      showloading: false,
      curHeight: 100,
      folderData: null,
      fatherFolderId: "0",
      dialogFolderTitle: "新增分类",
      formConfigFolder: resourceFolderForm,
      typeFolder: "add",
      dialogFolderShow: false,
      data: [],
      tableIndex: "",
      selectItem: [],
      username: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "FileName",
          label: "文件名称",
        },
        {
          prop: "FileSize",
          label: "文件大小",
        },
        {
          prop: "Description",
          label: "描述",
        },
        {
          prop: "UploadUser",
          label: "创建人",
        },
        {
          prop: "UploadTime",
          label: "创建时间",
        },
      ],
      // btnList: ["delete", "downloadRow"],
      btnList: ["delete", "edit", "lookViewRow", "downloadRow"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: presetFieldsForm,
      type: "add",

      fileInfo: {},
    };
  },
  methods: {
    getHeight() {
      this.curHeight = window.innerHeight - 146;
    },
    getDataEdit(e) {
      const id = this.fileInfo.Id;
      const name = e.name;
      const desc = e.desc;
      let self = this;
      self.showloading = true;
      AjaxCommon(
        `/api/ResourceFile/changefileinfo/${id}?newFileName=${name}&newDesc=${desc}`,
        "put",
        {}
      ).then((res) => {
        if (res?.data?.status == 200) {
          self.showloading = false;
          PopupCommon.notify("success", "编辑成功");
          self.initPage();
          self.dialogEditShow = false;
        } else {
          self.showloading = false;
          if (res) {
            PopupCommon.notify("error", res?.data?.msg);
          }
        }
      });
    },
    getData(e) {
      // api/ResourceFile/changefileinfo/111?newFileName=222&newDesc=333
      e.FileFolderId = this.tableIndex;
      let self = this;
      self.showloading = true;
      AjaxCommon(`/api/ResourceFile/uploadfile`, "postForm", e).then((res) => {
        console.log(res, "3333");
        if (res?.data?.status == 200) {
          self.showloading = false;
          PopupCommon.notify("success", "新增成功");
          self.initPage();
          self.dialogShow = false;
        } else {
          self.showloading = false;
          if (res) {
            PopupCommon.notify("error", res?.data?.msg);
          }
        }
      });
    },
    handleNodeClick(data) {
      this.tableIndex = data.id;
      this.initPage();
    },
    // 懒加载获取树形结构
    loadNode(node, resolve) {
      console.log(node.level, node.data.id);
      if (node.level == 0) {
        // node其实是需要展开树节点，但是第一次的node是个无用的数据，可以认为这个node是element给我们创建的，判断的话，就是level等于0
        this.getTreeData(0, resolve);
      } else {
        this.getTreeData(node, resolve);
      }
    },
    // 获取树形结构的数据
    getTreeData(node, resolve) {
      var searchNodeID = node ? node.data.id : null;
      AjaxCommon(
        `/api/folder?folderType=5&key=${searchNodeID}`,
        "get",
        null
      ).then((res) => {
        if (res.data.status == 200) {
          var data = res.data.response;
          data = data.map((r) => {
            return {
              id: r.Id,
              label: r.FolderName,
              children: [],
            };
          });
          console.log(data, "data.......");
          if (!node) {
            return resolve(data); // resolve是一个函数，它会接受一个数组，作为你要展开的节点的孩子节点，如果没有孩子节点，直接传一个空数组
          } else {
            if (data && data.length > 0) {
              return resolve(data); // 如果需要设置一个树节点，也可以在这里设置，比如说设置这个孩子节点是叶子节点（也就是不能展开的末节点），可以给其中的数据设置item.isLeaf = true
            } else {
              return resolve([]);
            }
          }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    append(data) {
      console.log(data, "data.................");
      this.folderData = data;
      this.fatherFolderId = data.id;
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增分类";
      this.dialogFolderShow = true;
    },

    remove(node, data) {
      console.log(node, data, "......................data");
      let self = this;
      const id = data.id;
      PopupCommon.confirm(`确定删除【${data.label}】？`)
        .then(() => {
          AjaxCommon("/api/folder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            console.log(res, "res...............");
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initLeftFolder(() => {
                self.initPage();
              });
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    renderContent(h, { node, data }) {
      // 删除按钮，暂时隐藏。放在tree-btn  类里面
      return (
        <span style="flex: 1;display: flex;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 8px;">
          <span>{node.label}</span>
          <span class="tree-btn">
            <span style="color: #409EFF;padding: 2px;border-radius: 2px;margin-right: 4px;">
              <i class="el-icon-plus" on-click={() => this.append(data)}></i>
            </span>
            <span style="padding: 2px;color: red;border-radius: 2px;">
              <i
                class="el-icon-delete"
                on-click={() => this.remove(node, data)}
              ></i>
            </span>
          </span>
        </span>
      );
    },
    dialogFolderClose() {
      this.dialogFolderShow = false;
    },
    formInputFolderChange(e) {
      console.log(e, "e...................");
    },
    folderSubmit(d) {
      console.log(d, "d..............d");
      let self = this;
      var params = {
        FolderName: d.FolderName,
        FatherFolderId: self.fatherFolderId,
        FolderType: 5,
      };
      var titleOpr = "新增成功";
      if (d.Id) {
        params["Id"] = d.Id;
        titleOpr = "编辑成功";
      }
      AjaxCommon(`/api/folder`, "postForm", params)
        .then((res) => {
          console.log(res, "res..................");
          if (res.data.status == 200) {
            PopupCommon.notify("success", titleOpr);
            if (self.fatherFolderId != "0") {
              const newChild = {
                id: res.data.response,
                label: d.FolderName,
                children: [],
              };
              if (!self.folderData.children) {
                this.$set(self.folderData, "children", []);
              }
              self.folderData.children.push(newChild);
            } else {
              self.initLeftFolder();
            }
            self.dialogFolderClose();
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        })
        .catch((err) => {
          PopupCommon.notify("error", err.message);
        });
    },
    showFolder() {
      this.fatherFolderId = "0";
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增分类";
      this.dialogFolderShow = true;
    },
    deleteFolder(item) {
      let self = this;
      const id = item.Id;
      console.log(item, "item");
      PopupCommon.confirm(`确定删除【${item.FolderName}】？`)
        .then(() => {
          AjaxCommon("/api/familyfolder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            console.log(res, "res...............");
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initLeftFolder();
              self.dialogFolderClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    singleBtnClick() {
      if (this.yzzdSelect.length == 0) {
        PopupCommon.notify("info", "请选择预置资源");
        return;
      }
      this.dialogShow = false;
      console.log(this.yzzdSelect, "this.yzzdSelect......");
    },
    singleHandleSelectionChange(e) {
      this.yzzdSelect = e;
    },
    deleteAll() {
      if (this.selectItem.length == 0) {
        PopupCommon.notify("info", "请先勾选数据");
        return;
      }
      PopupCommon.confirm("此操作将删除选择的数据, 是否继续?")
        .then(() => {
          // self.optReason = ""
          // self.dialogVisible = true
          // // optReason
          // const data = {
          // 	index: i,
          // 	data: d[i],
          // }
          // self.formData = data
          // // this.$emit("deleteRow", data)
          console.log(this.selectItem);
        })
        .catch(() => {
          // 这里尽量写下，否则会报警告异常。
          console.log("已取消删除");
        });
    },
    handleSelectionChange(d) {
      this.selectItem = d;
      console.log(d);
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    submit(d) {
      console.log(d);
      // let self = this
      // console.log(d)
      // if (d.id) {
      // 	AjaxCommon("/ccdc/cfg/device/device/edit", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 				this.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // } else {
      // 	delete d.id
      // 	AjaxCommon("/ccdc/cfg/device/device/add", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.username = "";
    },
    addClick() {
      // // 测试
      // AjaxCommon("/api/familyresouce/downloadfile/1", "get", null)

      if (this.tableIndex == "") {
        PopupCommon.notify("info", "请先选择左侧的资源分类");
        return;
      }
      this.type = "add";
      this.dialogShow = true;
      this.dialogTitle = "新增资源";
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    viewRow(d) {
      this.type = "look";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    lookViewRow(d) {
      const id = d.data.Id;
      let self = this;
      AjaxCommon("/api/ResourceFile/previewfile/" + id, "get", null).then(
        (res) => {
          console.log(res, "res..............");
          if (res.status == 200) {
            const finallyPath = self.publicPath + res.data.response;
            const link = document.createElement("a");
            link.target = "_blank";
            link.href = finallyPath;
            link.click();
            URL.revokeObjectURL(finallyPath); // 释放内存
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );
    },
    startDown() {
      this.showPwdJudge = false;
      const item = this.currentSelectDown;
      const id = item.Id;
      // let self = this
      AjaxCommon("/api/ResourceFile/downloadfile/" + id, "getBlob", null).then(
        (res) => {
          if (res?.status == 200) {
            console.log(1111111111);
            // var data = self.stringToArrayBuffer(res.data)
            var blob = new Blob([res.data]);
            const href = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.download = item.FileName;
            link.href = href;
            link.click();
            try {
              document.body.removeChild(link);
            } catch (error) {
              console.log(error.message);
            }
            URL.revokeObjectURL(href); // 释放内存
          } else {
            PopupCommon.notify("error", res?.data?.msg ?? "资源未找到");
          }
        }
      );
    },
    downloadRow(d) {
      this.currentSelectDown = d.data;
      this.showPwdJudge = true;
    },
    stringToArrayBuffer(str) {
      console.log(str, "str....................");
      var buf = new ArrayBuffer(str.length);
      var bufView = new Uint8Array(buf);
      for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    },
    editRow(d) {
      const id = d.data.Id;
      const data = d.data;
      console.log(id, data);
      this.fileInfo = data;
      // this.Description=data.Description
      // this.FileName=data.FileName
      this.dialogEditShow = true;
    },
    deleteRow(d) {
      console.log(d);
      const id = d.data.Id;
      let self = this;
      AjaxCommon("/api/ResourceFile?id=" + id, "delete", {
        optReason: d.optReason,
      }).then((res) => {
        console.log(res, "res...............");
        if (res.data.status == 200) {
          PopupCommon.notify("success", "删除成功");
          self.initPage();
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    // 初始化事件
    initPage() {
      let self = this;
      var id = this.tableIndex;
      AjaxCommon("/api/ResourceFile/detail?id=" + id, "get").then((res) => {
        if (res.data.status == 200) {
          self.dataSource = res.data.response;
          self.dataSource &&
            self.dataSource.length > 0 &&
            self.dataSource.map((t) => {
              if (parseFloat(t.FileSize) > 1024) {
                t.FileSize = (parseFloat(t.FileSize) / 1024).toFixed(2) + "M";
              } else {
                t.FileSize = t.FileSize + "KB";
              }
              return t;
            });
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    initLeftFolder(callback) {
      let self = this;
      self.data = [];
      AjaxCommon("/api/folder/GetFullFolder?FolderType=5", "get", null).then(
        (res) => {
          if (res.data.status == 200) {
            let treeDataList = [];
            Utility.createTreeData(res.data.response, treeDataList);
            self.data = treeDataList;
            if (treeDataList && treeDataList.length > 0) {
              console.log("1111111111111");
              self.tableIndex = treeDataList[0].id;
              self.$nextTick(() => {
                self.$refs.tree.setCurrentKey(treeDataList[0].id);
              });
              callback && callback();
            } else {
              self.tableIndex = "";
              self.tableList = [];
            }
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );

      // let self = this
      // self.data = []
      // AjaxCommon("/api/folder?folderType=5", "get", null).then((res) => {
      // 	if (res.data.status == 200) {
      // 		var data = res.data.response
      // 		data = data.map((r) => {
      // 			return {
      // 				id: r.Id,
      // 				label: r.FolderName,
      // 				children: [],
      // 			}
      // 		})
      // 		self.data = data
      // 		setTimeout(() => {
      // 			if (data && data.length > 0) {
      // 				console.log("self...............................")
      // 				self.tableIndex = data[0].id
      // 				self.$nextTick(() => {
      // 					self.$refs.tree.setCurrentKey(data[0].id)
      // 				})
      // 				callback && callback()
      // 			} else {
      // 				self.tableIndex = ""
      // 				self.tableList = []
      // 			}
      // 		}, 1000)
      // 	} else {
      // 		PopupCommon.notify("error", res.data.msg)
      // 	}
      // })
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
      this.initLeftFolder(() => {
        this.initPage();
      });
    });

    /*窗口自适应，关键代码*/
    window.onresize = () => {
      this.getHeight();
    };
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}

.flex .flex-left {
  width: 350px;
  margin-right: 10px;
}

.flex .flex-right {
  flex: 1;
}

.flex .flex-left .navigationBar {
  height: 36px;
  line-height: 36px;
  background-color: #fff;
  margin-top: 10px;
}

.flex .flex-left .flex-tree {
  background-color: #fff;
  margin-top: 10px;
  height: calc(100vh - 168px);
  overflow-y: auto;
  padding: 10px;
}

.flex .flex-left .flex-tree .tree-item {
  height: 32px;
  line-height: 32px;
  margin: 5px 10px;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .tree-item:hover {
  background-color: #e4f1fe;
}
.flex .flex-left .flex-tree .hover {
  background-color: #e4f1fe;
}

.flex .flex-left .navigationBar label {
  text-align: left;
  font-size: 16px;
  color: #333;
  margin-left: 10px;
}

.flex .flex-left .navigationBar span {
  float: right;
  margin-right: 10px;
  color: #333;
  cursor: pointer;
}

.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree-btn {
  color: red;
}
</style>
